from rest_framework.viewsets import GenericViewSet,ViewSet

from apps.models import HouseKeeping, User
from apps.serializers.ListHousekeeping import ListThingSerializer, AddWishSerializer
from apps.utils.common_function import log_error
from apps.utils.common_response import APIResponse


class IncreaseWish(ViewSet):
    queryset = HouseKeeping.objects.all()
    def create(self, request):
        try:
            username = request.GET.get('username', None)
            thingId = request.GET.get('thingId', None)

            if username and thingId:
                # User模型的实例
                user = User.objects.get(username=username)
                thing = HouseKeeping.objects.get(pk=thingId)
                print(thing.wish_count, type(thing.collect_count))
                if thing.wish_count >= 1:
                    return APIResponse(msg='心愿单已添加啦,请不要重复添加~')
                # 一个包含单个元素的QuerySet对象
                if user not in thing.wish.all():
                    # print(thing.collect.all())
                    thing.wish_count += 1
                    thing.wish.add(user)
                    thing.save()
                serializer = ListThingSerializer()
                return APIResponse(code=0, msg='心愿单添加成功', data=serializer.data)
        except HouseKeeping.DoesNotExist:
            log_error(request, '操作失败')
            return APIResponse(code=1, msg='操作失败')

class GetWishThingListView(GenericViewSet):
    def list(self, request):
        try:
            # 前端需要拿到用户名
            username = request.GET.get('username')
            # 如果有当前用户名的话
            if username:
                user = User.objects.get(username=username)
                # 反向关联
                thing = user.wish_things.all()
                serializer = ListThingSerializer(thing, many=True)
                return APIResponse(msg='该用户收藏数据', data=serializer.data)
            else:
                return APIResponse(code=1, msg='用户名不存在')
        except Exception as e:
            log_error(request, '操作失败' + str(e))
            return APIResponse(code=1, msg='获取收藏失败')


# 移除心愿单
class RemoveWishUser(GenericViewSet):
    def create(self, request):
        try:
            username = request.GET.get('username')
            thingId = request.GET.get('thingId')
            if username=='' or thingId=='':
                return APIResponse(code=1, msg='参数不能为空')
            user = User.objects.get(username=username)
            thing = HouseKeeping.objects.get(pk=thingId)
            # 看用户名在不在里面
            if user in thing.wish.all():
                thing.wish.remove(user)
                thing.wish_count -= 1
                thing.save()
        except HouseKeeping.DoesNotExist:
            log_error(request, '操作失败')
            return APIResponse(code=1, msg='操作失败')
        return APIResponse(code=0, msg='移除成功')
